<template>
  <div class="departements">
    <el-card>
      <template #header>
        <div>组织架构</div>
      </template>
      <div style="width: 80%; margin: 0 auto">
        <Treeitem :item="topInfo" style="width: 100%" @getDate="getDate" />
        <hr>
        <el-tree
          :data="treeDate"
          :props="{ label: 'name', children: 'children' }"
        >
          <template v-slot="{ data }">
            <Treeitem :item="data" style="width: 100%" @getDate="getDate" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <Add :init-tree-data="initTreeData" @getDate="getDate" />
  </div>
</template>

<script>
import { companyDepartment } from '@/api/departments'
import Treeitem from './components/treeItem.vue'
import Add from './components/add.vue'
export default {
  components: {
    Treeitem,
    Add
  },
  data() {
    return {
      treeDate: [],
      initTreeData: [],
      topInfo: {
        name: '传智',
        manager: '负责人',
        id: '',
        top: true
      }
    }
  },
  created() {
    this.getDate()
  },
  methods: {
    async getDate() {
      const res = await companyDepartment()
      this.initTreeData = res.data.depts
      // 将数据传入changeDate函数中 pid为''的是没有子结构的
      this.treeDate = this.changeDate(res.data.depts, '')
      this.topInfo.name = res.data.companyName
      // console.log(res.data.depts)
    },
    // 接收传过来的数组数据和空字符串
    changeDate(arr, str = '') {
      // 通过数组的filter的方法来查找满足pid为空的 返回true
      // pid为空的是父结构
      // 再通过递归来查找子结构 子结构的pid为父节后的id值
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeDate(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departements {
  padding: 15px;
}
</style>
